package com.example.shoppingmall.cotroller;

import com.alibaba.fastjson.JSONArray;
import com.example.shoppingmall.pojo.*;
import com.example.shoppingmall.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;


@Controller
//@RequestMapping("/panel")
public class PanelController {

    @Autowired
    ImpExportService impExportService;
    @Autowired
    PictureService pictureService;
    @Autowired
    StoreService storeService;
    @Autowired
    StoreClerkService storeClerkService;

    List<ImpExport> expList = new ArrayList<>();
    List<ImpState> stateList = new ArrayList<>();
    List<Picture> picList = new ArrayList<>();
    List<Store> stoList = new ArrayList<>();
    List<StoreClerk> stcList = new ArrayList<>();
    List<Provinces> proList = new ArrayList<>();
    List<Cities> citList = new ArrayList<>();
    List<Areas> areList = new ArrayList<>();

    Integer file_states = null;
    //导入导出列表查询
    @RequestMapping("/explist")
    public String expList(@RequestParam(value="import_name",required = false)String import_name, @RequestParam(value="file_state",required = false)Integer file_state,
                          @RequestParam(value="currentPage",required = false)Integer currentPage, HttpSession session, Model model){
        if(session.getAttribute("stateList")==null){
            stateList = impExportService.stateList();
            session.setAttribute("stateList",stateList);
        }
        if(file_state!=null){
            file_states=file_state;
        }
        file_state=file_states;
        if(file_state==null){
            file_state=0;
        }
        Pages page = new Pages();
        Integer total = impExportService.total(import_name, file_state);
        page.setTotalPageCount(total);
        if(currentPage==null || currentPage==0){
            page.setCurrentPage(1);
        }else{
            page.setCurrentPage(currentPage);
        }
        Integer pageNo = (page.getCurrentPage()-1)*page.getPageSize();
        expList = impExportService.expList(import_name,file_state,pageNo,page.getPageSize());
        model.addAttribute("expList",expList);
        model.addAttribute("page",page);
        if(import_name!=null){
            model.addAttribute("import_name",import_name);
        }
        if (file_state!=null){
            model.addAttribute("file_state",file_state);
        }
        return "controlpanel/ietask";
    }

    /**
     * 下载文件
     * @param id
     * @param req
     * @param resp
     * @throws IOException
     */
    @RequestMapping("/csvUpdate")
    @ResponseBody
    public void csvUpdate(@RequestParam(value="id",required = false)Integer id, HttpServletRequest req, HttpServletResponse resp)throws IOException {
        ImpExport export = impExportService.getExp(id);
        File file = new File(export.getFile_path());
        if (file.exists()) {
            //设置相应类型application/octet-stream
            resp.setContentType("application/x-msdownload");
            //设置头信息                 Content-Disposition为属性名  附件形式打开下载文件   指定名称  为 设定的filename
            resp.setHeader("Content-Disposition", "attachment;filename=\"" + export.getFile_name() + "\"");
            //输入流写入输出流
            InputStream inputStream = new FileInputStream(file);
            ServletOutputStream ouputStream = resp.getOutputStream();
            byte b[] = new byte[1024];
            int n;
            //循环读取 !=-1读取完毕
            while ((n = inputStream.read(b)) != -1) {
                //写入到输出流 从0读取到n
                ouputStream.write(b, 0, n);
            }
            //关闭流、释放资源
            ouputStream.close();
            inputStream.close();
            export.setFile_state(1);
            int result = impExportService.update(export);
        }
    }

    /**
     * 图片列表
     * @param pic_ID
     * @param pic_name
     * @param currentPage
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("/piclist")
    public String picList(@RequestParam(value="pic_ID",required = false)Integer pic_ID, @RequestParam(value="pic_name",required = false)String pic_name,
                          @RequestParam(value="currentPage",required = false)Integer currentPage, HttpSession session, Model model){
        Pages page = new Pages();
        Integer total = pictureService.total(pic_ID,pic_name);
        page.setTotalPageCount(total);
        if(currentPage==null || currentPage==0){
            page.setCurrentPage(1);
        }else{
            page.setCurrentPage(currentPage);
        }
        Integer pageNo = (page.getCurrentPage()-1)*page.getPageSize();
        picList = pictureService.picList(pic_ID,pic_name,pageNo,page.getPageSize());
        model.addAttribute("picList",picList);
        model.addAttribute("page",page);
        if(pic_ID!=null){
            model.addAttribute("pic_ID",pic_ID);
        }
        if(pic_name!=null){
            model.addAttribute("pic_name",pic_name);
        }
        return "controlpanel/images";
    }

    /**
     * 门店列表
     * @param currentPage
     * @param model
     * @return
     */
    @RequestMapping("/stolist")
    public String stolist(@RequestParam(value="currentPage",required = false)Integer currentPage,Model model){
        Pages page = new Pages();
        Integer total = storeService.total();
        page.setTotalPageCount(total);
        if(currentPage==null || currentPage==0){
            page.setCurrentPage(1);
        }else{
            page.setCurrentPage(currentPage);
        }
        Integer pageNo = (page.getCurrentPage()-1)*page.getPageSize();
        stoList = storeService.stoList(pageNo,page.getPageSize());
        model.addAttribute("stoList",stoList);
        model.addAttribute("page",page);
        return "controlpanel/store";
    }

    /**
     * 门店删除
     * @param id
     * @return
     */
    @RequestMapping("/stoDel")
    @ResponseBody
    public Object stoDel(@RequestParam("id")Integer id){
        Map<Object,Object> map = new HashMap<>();
        int resukt = storeClerkService.stcoDel(id);
        int result = storeService.stoDelete(id);
        map.put("status","Yes");
        return JSONArray.toJSONString(map);
    }

    /**
     * 跳转至新增门店
     * @param model
     * @return
     */
    @RequestMapping("/tostoreAdd")
    public String tostoreAdd(Model model){
        proList = storeService.proList();
        model.addAttribute("proList",proList);
        return "controlpanel/store_add";
    }

    /**
     * ajax查询地区
     * @param provinceid
     * @param areas
     * @param model
     * @return
     */
    @RequestMapping("/getPca")
    @ResponseBody
    public Object getPca(@RequestParam(value="provinceid",required = false)Integer provinceid,@RequestParam(value="areas",required = false)Integer areas,
                         Model model){
        /*proList = storeService.proList();
        model.addAttribute("proList",proList);*/
        Map<Object,Object> map = new HashMap<>();
        if(provinceid!=null){
            citList = storeService.citList(provinceid);
            model.addAttribute("citList",citList);
        }else if(areas!=null){
            System.out.println(areas);
            areList = storeService.areList(areas);
            model.addAttribute("areList",areList);
        }
        return JSONArray.toJSONString(model);
    }

    /**
     * 新增门店
     * @param store_name
     * @param store_phone
     * @param linkman
     * @param files
     * @param provinceid
     * @param cityid
     * @param areas
     * @return
     */
    @RequestMapping("/stoAdd")
    public String stoAdd(@RequestParam("store")String store_name, @RequestParam("store_phone")String store_phone, @RequestParam("linkman")String linkman,
                         @RequestParam(value="files",required = false)MultipartFile files,@RequestParam("provinceid")Integer provinceid,@RequestParam("cityid")Integer cityid,
                         @RequestParam("areas")Integer areas,@RequestParam("address")String store_address){
        String path = ("F:\\qmxrj\\gyc\\Project\\logistics\\src\\main\\resources\\static\\images\\");
        File file = new File(path);
        Store store = new Store();
        System.out.println(files);
        if(!files.isEmpty()){
            if(!file.isDirectory()){
                file.mkdirs();
            }
            String oldname = files.getOriginalFilename();
            String newname = UUID.randomUUID().toString() + oldname.substring(oldname.lastIndexOf("."), oldname.length());
            try{
                files.transferTo(new File(file,newname));
            }catch (IOException e){
                e.printStackTrace();
            }
            store.setLogo(newname);
            Picture pr = new Picture();
            pr.setPic_ID(newname);
            pr.setPic_name(newname);
            int res = pictureService.add(pr);
        }
        Provinces pro = storeService.getProName(provinceid);
        String proName = pro.getProvince();
        Cities city = storeService.getCityName(cityid);
        String cityName = city.getCity();
        Areas area = storeService.getAreasName(areas);
        String areaName = area.getArea();
        store.setStore(store_name);
        store.setStore_phone(store_phone);
        store.setLinkman(linkman);
        store.setStore_area(proName+" "+cityName+" "+areaName);
        store.setProid(provinceid);
        store.setCityid(cityid);
        store.setAreaid(areas);
        store.setAddress(store_address);
        int result = storeService.stoAdd(store);
        if(result>0){
            return "redirect:/stolist";
        }
        return "redirect:/tostoreAdd";
    }

    /**
     * 跳转至修改门店
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/tostoreUpdate")
    public String tostoreUpdate(@RequestParam("id")Integer id,Model model){
        Store store = storeService.getSto(id);
        model.addAttribute("store",store);
        proList = storeService.proList();
        model.addAttribute("proList",proList);
        citList = storeService.citList(store.getProid());
        model.addAttribute("citList",citList);
        areList = storeService.areList(store.getCityid());
        model.addAttribute("areList",areList);
        return "controlpanel/store_update";
    }



    /**
     * 修改门店
     * @param store_name
     * @param store_phone
     * @param linkman
     * @param files
     * @param provinceid
     * @param cityid
     * @param areas
     * @return
     */
    @RequestMapping("/stoUpdate")
    public String stoUpdate(@RequestParam("id")Integer id,@RequestParam("store")String store_name, @RequestParam("store_phone")String store_phone, @RequestParam("linkman")String linkman,
                         @RequestParam(value="files",required = false)MultipartFile files,@RequestParam("provinceid")Integer provinceid,@RequestParam("cityid")Integer cityid,
                         @RequestParam("areas")Integer areas,@RequestParam("address")String store_address){
        String path = ("F:\\qmxrj\\gyc\\Project\\logistics\\src\\main\\resources\\static\\images\\");
        File file = new File(path);
        Store store = new Store();
        if(!files.isEmpty()){
            if(!file.isDirectory()){
                file.mkdirs();
            }
            String oldname = files.getOriginalFilename();
            String newname = UUID.randomUUID().toString() + oldname.substring(oldname.lastIndexOf("."), oldname.length());
            try{
                files.transferTo(new File(file,newname));
            }catch (IOException e){
                e.printStackTrace();
            }
            store.setLogo(newname);
            Picture pr = new Picture();
            pr.setPic_ID(newname);
            pr.setPic_name(newname);
            int res = pictureService.add(pr);
        }
        Provinces pro = storeService.getProName(provinceid);
        String proName = pro.getProvince();
        Cities city = storeService.getCityName(cityid);
        String cityName = city.getCity();
        Areas area = storeService.getAreasName(areas);
        String areaName = area.getArea();
        store.setStore(store_name);
        store.setStore_phone(store_phone);
        store.setLinkman(linkman);
        store.setStore_area(proName+" "+cityName+" "+areaName);
        store.setProid(provinceid);
        store.setCityid(cityid);
        store.setAreaid(areas);
        store.setAddress(store_address);
        store.setId(id);
        int result = storeService.stoUpdate(store);
        if(result>0){
            return "redirect:/stolist";
//            return "redirect:/panel/stolist";
        }
        return "redirect:/tostoreUpdate";
//        return "redirect:/panel/tostoreUpdate";
    }

    /**
     * 查询门店的店员
     * @param store_id
     * @param currentPage
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("/stclist")
    public String stclist(@RequestParam(value="store_id",required = false)Integer store_id,@RequestParam(value="currentPage",required = false)Integer currentPage
            ,Model model,HttpSession session){
        if(model.addAttribute("stoteName")==null){
            stcList = storeClerkService.getStoreName();
            model.addAttribute("stoteName",stcList);
        }
        Pages page = new Pages();
        Integer total = storeClerkService.total(store_id);
        page.setTotalPageCount(total);
        if(currentPage==null || currentPage==0){
            page.setCurrentPage(1);
        }else{
            page.setCurrentPage(currentPage);
        }
        Integer pageNo = (page.getCurrentPage()-1)*page.getPageSize();
        stcList = storeClerkService.stcList(store_id,pageNo,page.getPageSize());
        session.setAttribute("store_id",store_id);
        model.addAttribute("stcList",stcList);
        model.addAttribute("page",page);
        return "controlpanel/store_clerklist";
    }

    /**
     * 跳转到新增店员
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/toAddClerk")
    public Object toAddClerk(@RequestParam("id")Integer id, Model model){
        Map<Object,Object> map = new HashMap<>();
        stcList = storeClerkService.getStoreName();
        model.addAttribute("stoteName",stcList);
        return "controlpanel/store_addclerk";
    }


    /**
     * 新增店员
     * @param store_id
     * @param clerk_phone
     * @return
     */
    @RequestMapping("/AddClerk")
    public String AddClerk(@RequestParam("store_id")Integer store_id,@RequestParam("clerk_name")String clerk_name,@RequestParam("clerk_phone")String clerk_phone){
        StoreClerk storeClerk = new StoreClerk();
        storeClerk.setStore_id(store_id);
        storeClerk.setClerk_name(clerk_name);
        storeClerk.setClerk_phone(clerk_phone);
        int result = storeClerkService.stcAdd(storeClerk);
        if(result>0){
            return "redirect:/stclist?store_id="+store_id;
//            return "redirect:/panel/stclist?store_id="+store_id;
        }else{
            return "controlpanel/Page_skipping";
        }
    }

    /**
     * ajax验证
     * @param clerk_phone
     * @param store_id
     * @return
     */
    @RequestMapping("/stcPhone")
    @ResponseBody
    public Object stcPhone(@RequestParam("clerk_name")String clerk_name,@RequestParam("clerk_phone")String clerk_phone,@RequestParam("store_id")Integer store_id){
        Map<Object,Object> map = new HashMap<>();
        StoreClerk clerk = storeClerkService.getClerkName(clerk_name,store_id);
        if(clerk!=null){
            map.put("stcName","Yes");
            StoreClerk storeClerk = storeClerkService.getClerkPhone(clerk_phone,store_id);
            if(storeClerk!=null){
                map.put("stcClerkPhone","Yes");
            }else{
                map.put("stcClerkPhone","No");
            }
        }else{
            map.put("stcName","No");
            StoreClerk storeClerk = storeClerkService.getClerkPhone(clerk_phone,store_id);
            if(storeClerk!=null){
                map.put("stcClerkPhone","Yes");
            }else{
                map.put("stcClerkPhone","No");
            }
        }
        return JSONArray.toJSONString(map);
    }

    /**
     * 店员删除
     * @param id
     * @return
     */
    @RequestMapping("/stcDel")
    @ResponseBody
    public Object stcDel(@RequestParam("id")Integer id){
        Map<Object,Object> map = new HashMap<>();
        int result = storeClerkService.stcDelete(id);
        if(result>0){
            map.put("status","Yes");
        }
        return JSONArray.toJSONString(map);
    }

}
